<?php

namespace app\admin\controller\exam;

use app\admin\model\exam\CateModel;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 试题分类
 * @icon fa fa-circle-o
 */
class Cate extends Backend
{
    protected $noNeedRight = ['*'];

    /**
     * CateModel模型对象
     * @var \app\admin\model\exam\CateModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\CateModel;
        $query       = $this->model->order('sort asc,id asc');

        $kind = input('kind/s', 'all');
        if ($kind != 'all') {
            $query->where('kind', $kind);
        }

        if($this->auth->id != 1)
        {
            $agalist = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
            if($agalist['group_id'] == 3)
            {
                $tlist = Db::name('classes_teacher')->where('user_id',$this->auth->id)->find();
                $admin_id = $tlist['admin_id'];
            }
            else
            {
                $admin_id = $this->auth->id;
            }
            $query->where('uid', $admin_id);
        }

        $tree = Tree::instance();
        $tree->init(collection($query->select())->toArray(), 'parent_id');
        $this->parentlist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("parentList", $this->parentlist);
        $this->view->assign("usesList", $this->model->getUsesList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            // if ($this->request->request('keyField')) {
            //     return $this->selectpage();
            // }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $search = $this->request->request("search");
            $kind   = $this->request->request("kind");
            $parent_id   = $this->request->request("parent_id");
            //构造父类select列表选项数据
            $list = [];

            foreach ($this->parentlist as $k => $v) {
                /*if ($search) {
                    if ($v['kind'] == $kind) {
                        $list[] = $v;
                    }
                } else {
                    $list[] = $v;
                }*/
                if($parent_id)
                {
                    if ($v['parent_id'] == $parent_id)
                    {
                        $list[] = $v;
                        foreach ($this->parentlist as $kk => $vv)
                        {
                            if ($vv['parent_id'] == $v['id'])
                            {
                                $list[] = $vv;
                                foreach ($this->parentlist as $kkk => $vvv)
                                {
                                    if ($vvv['parent_id'] == $vv['id'])
                                    {
                                        $list[] = $vvv;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if ($v['parent_id'] == 0) {
                        $list[] = $v;
                    }
                }
            }

            $total  = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Selectpage搜索
     * @internal
     */
    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                $query->where('uid', "=", get_admin_id($this->auth->id));
                $query->where('level', "=", 4);
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
//        return parent::selectpage();
    }
    /**
     * 获取有题目的分类
     * @internal
     */
    public function getQuestionCate()
    {
        if ($cate_ids = $this->request->request("keyValue", "")) {
            $list = CateModel::whereIn('id', $cate_ids)->select();
        } else {
            $agalist = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
            if($agalist['group_id'] == 3)
            {
                $tlist = Db::name('classes_teacher')->where('user_id',$this->auth->id)->find();
                $admin_id = $tlist['admin_id'];
            }
            else
            {
                $admin_id = $this->auth->id;
            }
            $ids  = Db::name('exam_question')->where('uid',$admin_id)->group('cate_id')->field('cate_id')->select();
            $list = $ids ? CateModel::whereIn('id', array_column($ids, 'cate_id'))->select() : [];
        }
        return json(['list' => $list, 'total' => count($list)]);
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if($params['parent_id_t'] != 0)
                {
                    $params['parent_id'] = $params['parent_id_t'];
                }
                unset($params['parent_id_t']);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $this->setLevel($params);
                    $agalist = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
                    if($agalist['group_id'] == 3)
                    {
                        $tlist = Db::name('classes_teacher')->where('user_id',$this->auth->id)->find();
                        $admin_id = $tlist['admin_id'];
                    }
                    else
                    {
                        $admin_id = $this->auth->id;
                    }
                    $params['uid'] = $admin_id;

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $agalist = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
        if($agalist['group_id'] == 3)
        {
            $tlist = Db::name('classes_teacher')->where('user_id',$this->auth->id)->find();
            $admin_id = $tlist['admin_id'];
        }
        else
        {
            $admin_id = $this->auth->id;
        }
        $parentlist = Db::name('exam_cate')->where(['parent_id'=>0,'uid'=>$admin_id,'deletetime'=>null])->select();
        $this->view->assign("parentList", $parentlist);
        return $this->view->fetch();
    }
    public function son_cate()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if($params['qid'] == 0){
                return json(['code'=>1,'msg'=>'','list'=>[]]);
            }
            $list = Db::name('exam_cate')->where(['parent_id'=>$params['qid'],'deletetime'=>null])->select();
            if(!empty($list))
            {
                return json(['code'=>100,'msg'=>'','list'=>$list]);
            }
            return json(['code'=>1,'msg'=>'','list'=>[]]);
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if(!empty($params['remark']))
                    {
                        Db::name('exam_question')->where('cate_id','in',$ids)->update(['describe'=>$params['remark']]);
                    }

                    $this->setLevel($params, $row);
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 设置层级
     * @param $params
     */
    protected function setLevel(&$params, $row = null)
    {
        $params['parent_id'] = $params['parent_id'] ?? 0;

        if (!$params['parent_id']) {
            $params['level'] = 1;
        } else {
            $parent = CateModel::get($params['parent_id']);

            // 编辑时
            if ($row) {
                if ($params['parent_id'] == $row['id']) {
                    throw new \Exception('不能将当前分类设置为父级分类');
                }
                if ($parent['kind'] != $params['kind']) {
                    throw new \Exception('不能将当前分类设置为其他种类的下级');
                }
                $child_ids = CateModel::where('parent_id', $row['id'])->column('id');
                if (in_array($params['parent_id'], $child_ids)) {
                    throw new \Exception('不能将当前分类的子级设置为当前分类的父级');
                }
            }

            if ($parent['level'] == 1) {
                $params['level'] = 2;
            } else if ($parent['level'] == 2) {
                $params['level'] = 3;
            }else if ($parent['level'] == 3) {
                $params['level'] = 4;
            } else {
                throw new \Exception('错误：最多添加4级分类，请重新选择父级类别');
            }
        }
    }
    
    public function del_all()
    {
        $ids = $this->request->post("ids");
        $data = [
            'deletetime' => time(),
        ];
        //一级
        Db::name('exam_cate')->where('id','in',$ids)->update($data);
        Db::name('exam_question')->where('cate_id','in',$ids)->update($data);
        $where['parent_id'] = ['in',$ids];
        $where['deletetime'] = null;

        $list = Db::name('exam_cate')->where($where)->select();
        $son_ids = '';
        $son_son_ids = '';
        $son_son_son_ids = '';
        $sids = '';

        if(!empty($list))
        {
            foreach ($list as $k => $v)
            {
                $son_ids .= $v['id'].',';
            }
            $son_ids = trim($son_ids,',');
            $son_where['parent_id'] = ['in',$son_ids];
            $son_where['deletetime'] = null;
            //二级
            Db::name('exam_cate')->where($where)->update($data);
            Db::name('exam_question')->where('cate_id','in',$son_ids)->update($data);

            $son_list = Db::name('exam_cate')->where($son_where)->select();

            if(!empty($son_list))
            {
                foreach ($son_list as $k => $v)
                {
                    $son_son_ids .= $v['id'].',';
                }
                $son_son_ids = trim($son_son_ids,',');
                $son_son_where['parent_id'] = ['in',$son_son_ids];
                $son_son_where['deletetime'] = null;
                //三级
                Db::name('exam_cate')->where($son_where)->update($data);
                Db::name('exam_question')->where('cate_id','in',$son_son_ids)->update($data);

                $son_son_list = Db::name('exam_cate')->where($son_son_where)->select();

                if(!empty($son_son_list))
                {
                    foreach ($son_son_list as $k => $v)
                    {
                        $son_son_son_ids .= $v['id'].',';
                    }
                    $son_son_son_ids = trim($son_son_son_ids,',');
                    $son_son_son_where['parent_id'] = ['in',$son_son_son_ids];
                    $son_son_son_where['deletetime'] = null;
                    //四级
                    Db::name('exam_cate')->where($son_son_where)->update($data);
                    Db::name('exam_question')->where('cate_id','in',$son_son_son_ids)->update($data);

                    $slist = Db::name('exam_cate')->where($son_son_son_where)->select();

                    if(!empty($slist))
                    {
                        foreach ($slist as $k => $v)
                        {
                            $sids .= $v['id'].',';
                        }
                        $sids = trim($sids,',');
                        Db::name('exam_question')->where('cate_id','in',$sids)->update($data);
                    }
                }
            }
        }

        return json(['code'=>1,'data'=>'','msg'=>'','url'=>'/abdmin.php/exam.cate/del_all','wait'=>3]);
    }
    public function expandlink()
    {
        $id = $this->request->request("id");
        if ($this->request->isPost()) {
            $cate_id = $this->request->request("cate_id");
            $other_url = $this->request->request("other_url");
            $other_name = $this->request->request("other_name");

            Db::name('exam_question')->where('cate_id',$cate_id)->update(['other_url'=>$other_url,'other_name'=>$other_name]);
//            $this->success();
            echo "<script>alert('修改成功');parent.location.reload();</script>";die;
        }
        $this->view->assign("cate_id", $id);
        return $this->view->fetch();
    }
}
